package com.yupi.yupicturebackend.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import com.qcloud.cos.model.COSObject;
import com.qcloud.cos.model.COSObjectInputStream;
import com.qcloud.cos.utils.IOUtils;
import com.yupi.yupicturebackend.annotation.AuthCheck;
import com.yupi.yupicturebackend.common.BaseResponse;
import com.yupi.yupicturebackend.common.ResultUtils;
import com.yupi.yupicturebackend.config.CosClientConfig;
import com.yupi.yupicturebackend.constant.UserConstant;
import com.yupi.yupicturebackend.exception.BusinessException;
import com.yupi.yupicturebackend.exception.ErrorCode;
import com.yupi.yupicturebackend.manager.CosManager;
import com.yupi.yupicturebackend.model.entity.User;
import com.yupi.yupicturebackend.model.vo.LoginUserVO;
import io.github.classgraph.utils.FileUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.UUID;

/**
 * @author 边拾柱
 * @date 2025/3/6 11:55
 */
@RestController
@Slf4j
public class FileController {

    @Resource
    private CosManager cosManager;
    @Resource
    private CosClientConfig cosClientConfig;

    /**
     * 测试文件上传
     *
     * @param multipartFile
     * @return
     */
//    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    @PostMapping("/test/upload")
    /**
     *@RequestPart用于将multipart/form-data类型数据映射到控制器处理方法的参数中
     * @RequestParam 也可以使用
     */
    public BaseResponse<String> testUploadFile(@RequestPart("file") MultipartFile multipartFile, User loginUser) {
        // 文件目录
        String filename = multipartFile.getOriginalFilename();
        String uuID = UUID.randomUUID().toString();

        String filepath = String.format("/avator/%s/%s_%s.%s", loginUser.getId(),  DateUtil.formatDate(new Date()), uuID,
                FileUtil.getSuffix(filename));
        File file = null;
        try {
            // 上传文件
//            创建临时文件
            file = File.createTempFile(filepath, null);
//            将文件写入临时文件
            multipartFile.transferTo(file);
//            将临时文件上传到cos
            cosManager.putObject(filepath, file);
            // 返回可访问地址
            return ResultUtils.success(cosClientConfig.getHost() + filepath);
        } catch (Exception e) {
            log.error("file upload error, filepath = " + filepath, e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "上传失败");
        } finally {
            if (file != null) {
                // 删除临时文件
                boolean delete = file.delete();
                if (!delete) {
                    log.error("file delete error, filepath = {}", filepath);
                }
            }
        }
    }

    /**
     * 测试文件下载
     *
     * @param filepath 文件路径
     * @param response 响应对象
     */
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    @GetMapping("/test/download/")
    public void testDownloadFile(String filepath, HttpServletResponse response) throws IOException {

//        // 设置响应头
//        //这个是告诉浏览器下载文件类型，不然浏览器不会正常解析
//        response.setContentType("application/octet-stream;charset=UTF-8");
////        指示浏览器将响应内容作为附件下载，并指定下载文件的名称
////        attachment 参数告诉浏览器这是一个要下载的文件，而不是直接在浏览器中打开。
//        response.setHeader("Content-Disposition", "attachment; filename=" + filepath);
//        try(COSObjectInputStream cosObjectInput = cosManager.getObject(filepath).getObjectContent()) {
//            IoUtil.copy(cosObjectInput, response.getOutputStream());
//        }catch (Exception e) {
//            log.error("file download error, filepath = " + filepath, e);
//            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "下载失败");
//        }


        COSObjectInputStream cosObjectInput = null;
        try {
            COSObject cosObject = cosManager.getObject(filepath);
            cosObjectInput = cosObject.getObjectContent();
            // 处理下载到的流
            byte[] bytes = IOUtils.toByteArray(cosObjectInput);
            // 设置响应头
            response.setContentType("application/octet-stream;charset=UTF-8");
            response.setHeader("Content-Disposition", "attachment; filename=" + filepath);
            // 写入响应
            response.getOutputStream().write(bytes);
//            将缓冲区中的数据强制刷新并写入到客户端。确保所有已写入的数据都被发送出去，避免数据滞留在缓冲区中未被传输。
            response.getOutputStream().flush();
        } catch (Exception e) {
            log.error("file download error, filepath = " + filepath, e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "下载失败");
        } finally {
            if (cosObjectInput != null) {
                cosObjectInput.close();
            }
        }
    }


}
